<?php
//这里是公用函数
function p($arr){
    echo '<pre>'.print_r($arr,true).'</pre>';
}
/**
 * 网站域名配置
 * 
 */
function d_name($key='root'){
    $arr = array(
        'root'=>'denke.com',
        'www'=>'denke.com',
        'hw'=>'http://denke.com',
        'm'=>'wap.php'
    );
    return $arr[$key];
}

//获取配置信息
function _setting($name='email',$key=1){
    $list = M('setting')->where(array('name'=>$name))->find();
    if($key){
        return json_decode($list['data'],true);
    }
    return $list;
}

//获取ip所在城市
function ip_add($ip,$key='city'){
    $ipInfoApi= 'http://ip.taobao.com/service/getIpInfo.php?ip='.$ip;
    $areaInfo= file_get_contents($ipInfoApi);
    $areaInfo= json_decode($areaInfo,true);
    if($key){
        return $areaInfo['data']['city'];
        exit;
    }
    return  $areaInfo;
}


/**
 * 检测当前用户是否为管理员
 * @return boolean true-管理员，false-非管理员
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function is_administrator($uid = null){
    $uid = is_null($uid) ? is_login() : $uid;
    return $uid && (intval($uid) === C('USER_ADMINISTRATOR'));
}

/**
 * 字符串转换为数组，主要用于把分隔符调整到第二个参数
 * @param  string $str  要分割的字符串
 * @param  string $glue 分割符
 * @return array
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function str2arr($str, $glue = ','){
    return explode($glue, $str);
}

/**
 * 数组转换为字符串，主要用于把分隔符调整到第二个参数
 * @param  array  $arr  要连接的数组
 * @param  string $glue 分割符
 * @return string
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function arr2str($arr, $glue = ','){
    return implode($glue, $arr);
}

/**
 * 字符串截取，支持中文和其他编码
 * @static
 * @access public
 * @param string $str 需要转换的字符串
 * @param string $start 开始位置
 * @param string $length 截取长度
 * @param string $charset 编码格式
 * @param string $suffix 截断显示字符
 * @return string
 */
function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true) {
    $str = strip_tags($str);
    if(function_exists("mb_substr"))
        $slice = mb_substr($str, $start, $length, $charset);
    elseif(function_exists('iconv_substr')) {
        $slice = iconv_substr($str,$start,$length,$charset);
        if(false === $slice) {
            $slice = '';
        }
    }else{
        $re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
        $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
        $re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
        $re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
        preg_match_all($re[$charset], $str, $match);
        $slice = join("",array_slice($match[0], $start, $length));
    }
    return $suffix ? $slice.'...' : $slice;
}

/**
 * 系统加密方法
 * @param string $data 要加密的字符串
 * @param string $key  加密密钥
 * @param int $expire  过期时间 单位 秒
 * @return string
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function think_encrypt($data, $key = '', $expire = 0) {
    $key  = md5(empty($key) ? C('DATA_AUTH_KEY') : $key);
    $data = base64_encode($data);
    $x    = 0;
    $len  = strlen($data);
    $l    = strlen($key);
    $char = '';

    for ($i = 0; $i < $len; $i++) {
        if ($x == $l) $x = 0;
        $char .= substr($key, $x, 1);
        $x++;
    }

    $str = sprintf('%010d', $expire ? $expire + time():0);

    for ($i = 0; $i < $len; $i++) {
        $str .= chr(ord(substr($data, $i, 1)) + (ord(substr($char, $i, 1)))%256);
    }
    return str_replace(array('+','/','='),array('-','_',''),base64_encode($str));
}

/**
 * 系统解密方法
 * @param  string $data 要解密的字符串 （必须是think_encrypt方法加密的字符串）
 * @param  string $key  加密密钥
 * @return string
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function think_decrypt($data, $key = ''){
    $key    = md5(empty($key) ? C('DATA_AUTH_KEY') : $key);
    $data   = str_replace(array('-','_'),array('+','/'),$data);
    $mod4   = strlen($data) % 4;
    if ($mod4) {
       $data .= substr('====', $mod4);
    }
    $data   = base64_decode($data);
    $expire = substr($data,0,10);
    $data   = substr($data,10);

    if($expire > 0 && $expire < time()) {
        return '';
    }
    $x      = 0;
    $len    = strlen($data);
    $l      = strlen($key);
    $char   = $str = '';

    for ($i = 0; $i < $len; $i++) {
        if ($x == $l) $x = 0;
        $char .= substr($key, $x, 1);
        $x++;
    }

    for ($i = 0; $i < $len; $i++) {
        if (ord(substr($data, $i, 1))<ord(substr($char, $i, 1))) {
            $str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
        }else{
            $str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
        }
    }
    return base64_decode($str);
}

/**
 * 数据签名认证
 * @param  array  $data 被认证的数据
 * @return string       签名
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function data_auth_sign($data) {
    //数据类型检测
    if(!is_array($data)){
        $data = (array)$data;
    }
    ksort($data); //排序
    $code = http_build_query($data); //url编码并生成query字符串
    $sign = sha1($code); //生成签名
    return $sign;
}

/**
* 对查询结果集进行排序
* @access public
* @param array $list 查询结果
* @param string $field 排序的字段名
* @param array $sortby 排序类型
* asc正向排序 desc逆向排序 nat自然排序
* @return array
*/
function list_sort_by($list,$field, $sortby='asc') {
   if(is_array($list)){
       $refer = $resultSet = array();
       foreach ($list as $i => $data)
           $refer[$i] = &$data[$field];
       switch ($sortby) {
           case 'asc': // 正向排序
                asort($refer);
                break;
           case 'desc':// 逆向排序
                arsort($refer);
                break;
           case 'nat': // 自然排序
                natcasesort($refer);
                break;
       }
       foreach ( $refer as $key=> $val)
           $resultSet[] = &$list[$key];
       return $resultSet;
   }
   return false;
}

/**
 * 把返回的数据集转换成Tree
 * @param array $list 要转换的数据集
 * @param string $pid parent标记字段
 * @param string $level level标记字段
 * @return array
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function list_to_tree($list, $pk='id', $pid = 'pid', $child = '_child', $root = 0) {
    // 创建Tree
    $tree = array();
    if(is_array($list)) {
        // 创建基于主键的数组引用
        $refer = array();
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] =& $list[$key];
        }
        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId =  $data[$pid];
            if ($root == $parentId) {
                $tree[] =& $list[$key];
            }else{
                if (isset($refer[$parentId])) {
                    $parent =& $refer[$parentId];
                    $parent[$child][] =& $list[$key];
                }
            }
        }
    }
    return $tree;
}

/**
 * 将list_to_tree的树还原成列表
 * @param  array $tree  原来的树
 * @param  string $child 孩子节点的键
 * @param  string $order 排序显示的键，一般是主键 升序排列
 * @param  array  $list  过渡用的中间数组，
 * @return array        返回排过序的列表数组
 * @author yangweijie <yangweijiester@gmail.com>
 */
function tree_to_list($tree, $child = '_child', $order='id', &$list = array()){
    if(is_array($tree)) {
        $refer = array();
        foreach ($tree as $key => $value) {
            $reffer = $value;
            if(isset($reffer[$child])){
                unset($reffer[$child]);
                tree_to_list($value[$child], $child, $order, $list);
            }
            $list[] = $reffer;
        }
        $list = list_sort_by($list, $order, $sortby='asc');
    }
    return $list;
}

/**
 * 格式化字节大小
 * @param  number $size      字节数
 * @param  string $delimiter 数字和单位分隔符
 * @return string            格式化后的带单位的大小
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function format_bytes($size, $delimiter = '') {
    $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
    for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;
    return round($size, 2) . $delimiter . $units[$i];
}

/**
 * 设置跳转页面URL
 * 使用函数再次封装，方便以后选择不同的存储方式（目前使用cookie存储）
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function set_redirect_url($url){
    cookie('redirect_url', $url);
}

/**
 * 获取跳转页面URL
 * @return string 跳转页URL
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function get_redirect_url(){
    $url = cookie('redirect_url');
    return empty($url) ? __APP__ : $url;
}

/**
 * 处理插件钩子
 * @param string $hook   钩子名称
 * @param mixed $params 传入参数
 * @return void
 */
function hook($hook,$params=array()){
    \Think\Hook::listen($hook,$params);
}

/**
 * 获取插件类的类名
 * @param strng $name 插件名
 */
function get_addon_class($name){
    $class = "Addons\\{$name}\\{$name}Addon";
    return $class;
}

/**
 * 获取插件类的配置文件数组
 * @param string $name 插件名
 */
function get_addon_config($name){
    $class = get_addon_class($name);
    if(class_exists($class)) {
        $addon = new $class();
        return $addon->getConfig();
    }else {
        return array();
    }
}

/**
 * 插件显示内容里生成访问插件的url
 * @param string $url url
 * @param array $param 参数
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function addons_url($url, $param = array()){
    $url        = parse_url($url);
    $case       = C('URL_CASE_INSENSITIVE');
    $addons     = $case ? parse_name($url['scheme']) : $url['scheme'];
    $controller = $case ? parse_name($url['host']) : $url['host'];
    $action     = trim($case ? strtolower($url['path']) : $url['path'], '/');

    /* 解析URL带的参数 */
    if(isset($url['query'])){
        parse_str($url['query'], $query);
        $param = array_merge($query, $param);
    }

    /* 基础参数 */
    $params = array(
        '_addons'     => $addons,
        '_controller' => $controller,
        '_action'     => $action,
    );
    $params = array_merge($params, $param); //添加额外参数

    return U('Addons/execute', $params);
}

/**
 * 时间戳格式化
 * @param int $time
 * @return string 完整的时间显示
 * @author huajie <banhuajie@163.com>
 */
function time_format($time = NULL,$format='Y-m-d H:i'){
    $time = $time === NULL ? NOW_TIME : intval($time);
    return date($format, $time);
}

/**
 * 根据用户ID获取用户名
 * @param  integer $uid 用户ID
 * @return string       用户名
 */
function get_username($uid = 0){
    static $list;
    if(!($uid && is_numeric($uid))){ //获取当前登录用户名
        return session('user_auth.username');
    }

    /* 获取缓存数据 */
    if(empty($list)){
        $list = S('sys_active_user_list');
    }

    /* 查找用户信息 */
    $key = "u{$uid}";
    if(isset($list[$key])){ //已缓存，直接使用
        $name = $list[$key];
    } else { //调用接口获取用户信息
        $User = new User\Api\UserApi();
        $info = $User->info($uid);
        if($info && isset($info[1])){
            $name = $list[$key] = $info[1];
            /* 缓存用户 */
            $count = count($list);
            $max   = C('USER_MAX_CACHE');
            while ($count-- > $max) {
                array_shift($list);
            }
            S('sys_active_user_list', $list);
        } else {
            $name = '';
        }
    }
    return $name;
}

/**
 * 根据用户ID获取用户昵称
 * @param  integer $uid 用户ID
 * @return string       用户昵称
 */
function get_nickname($uid = 0){
    static $list;
    if(!($uid && is_numeric($uid))){ //获取当前登录用户名
        return session('user_auth.username');
    }

    /* 获取缓存数据 */
    if(empty($list)){
        $list = S('sys_user_nickname_list');
    }

    /* 查找用户信息 */
    $key = "u{$uid}";
    if(isset($list[$key])){ //已缓存，直接使用
        $name = $list[$key];
    } else { //调用接口获取用户信息
        $info = M('Member')->field('nickname')->find($uid);
        if($info !== false && $info['nickname'] ){
            $nickname = $info['nickname'];
            $name = $list[$key] = $nickname;
            /* 缓存用户 */
            $count = count($list);
            $max   = C('USER_MAX_CACHE');
            while ($count-- > $max) {
                array_shift($list);
            }
            S('sys_user_nickname_list', $list);
        } else {
            $name = '';
        }
    }
    return $name;
}

/**
 * 获取分类信息并缓存分类
 * @param  integer $id    分类ID
 * @param  string  $field 要获取的字段名
 * @return string         分类信息
 */
function get_category($id, $field = null){
    static $list;

    /* 非法分类ID */
    if(empty($id) || !is_numeric($id)){
        return '';
    }

    /* 读取缓存数据 */
    if(empty($list)){
        $list = S('sys_category_list');
    }

    /* 获取分类名称 */
    if(!isset($list[$id])){
        $cate = M('Category')->find($id);
        if(!$cate || 1 != $cate['status']){ //不存在分类，或分类被禁用
            return '';
        }
        $list[$id] = $cate;
        S('sys_category_list', $list); //更新缓存
    }
    return is_null($field) ? $list[$id] : $list[$id][$field];
}

/* 根据ID获取分类标识 */
function get_category_name($id){
    return get_category($id, 'name');
}

/* 根据ID获取分类名称 */
function get_category_title($id){
    return get_category($id, 'title');
}

/**
 * 获取文档模型信息
 * @param  integer $id    模型ID
 * @param  string  $field 模型字段
 * @return array
 */
function get_document_model($id = null, $field = null){
    static $list;

    /* 非法分类ID */
    if(!(is_numeric($id) || is_null($id))){
        return '';
    }

    /* 读取缓存数据 */
    if(empty($list)){
        $list = S('DOCUMENT_MODEL_LIST');
    }

    /* 获取模型名称 */
    if(empty($list)){
        $map   = array('status' => 1, 'extend' => 1);
        $model = M('Model')->where($map)->field(true)->select();
        foreach ($model as $value) {
            $list[$value['id']] = $value;
        }
        S('DOCUMENT_MODEL_LIST', $list); //更新缓存
    }

    /* 根据条件返回数据 */
    if(is_null($id)){
        return $list;
    } elseif(is_null($field)){
        return $list[$id];
    } else {
        return $list[$id][$field];
    }
}

/**
 * 解析UBB数据
 * @param string $data UBB字符串
 * @return string 解析为HTML的数据
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function ubb($data){
    //TODO: 待完善，目前返回原始数据
    return $data;
}

/**
 * 记录行为日志，并执行该行为的规则
 * @param string $action 行为标识
 * @param string $model 触发行为的模型名
 * @param int $record_id 触发行为的记录id
 * @param int $user_id 执行行为的用户id
 * @return boolean
 * @author huajie <banhuajie@163.com>
 */
function action_log($action = null, $model = null, $record_id = null, $user_id = null){

    //参数检查
    if(empty($action) || empty($model) || empty($record_id)){
        return '参数不能为空';
    }
    if(empty($user_id)){
        $user_id = is_login();
    }

    //查询行为,判断是否执行
    $action_info = M('Action')->getByName($action);
    if($action_info['status'] != 1){
        return '该行为被禁用或删除';
    }

    //插入行为日志
    $data['action_id']      =   $action_info['id'];
    $data['user_id']        =   $user_id;
    $data['action_ip']      =   ip2long(get_client_ip());
    $data['model']          =   $model;
    $data['record_id']      =   $record_id;
    $data['create_time']    =   NOW_TIME;

    //解析日志规则,生成日志备注
    if(!empty($action_info['log'])){
        if(preg_match_all('/\[(\S+?)\]/', $action_info['log'], $match)){
            $log['user']    =   $user_id;
            $log['record']  =   $record_id;
            $log['model']   =   $model;
            $log['time']    =   NOW_TIME;
            $log['data']    =   array('user'=>$user_id,'model'=>$model,'record'=>$record_id,'time'=>NOW_TIME);
            foreach ($match[1] as $value){
                $param = explode('|', $value);
                if(isset($param[1])){
                    $replace[] = call_user_func($param[1],$log[$param[0]]);
                }else{
                    $replace[] = $log[$param[0]];
                }
            }
            $data['remark'] =   str_replace($match[0], $replace, $action_info['log']);
        }else{
            $data['remark'] =   $action_info['log'];
        }
    }else{
        //未定义日志规则，记录操作url
        $data['remark']     =   '操作url：'.$_SERVER['REQUEST_URI'];
    }

    M('ActionLog')->add($data);

    if(!empty($action_info['rule'])){
        //解析行为
        $rules = parse_action($action, $user_id);

        //执行行为
        $res = execute_action($rules, $action_info['id'], $user_id);
    }
}

/**
 * 解析行为规则
 * 规则定义  table:$table|field:$field|condition:$condition|rule:$rule[|cycle:$cycle|max:$max][;......]
 * 规则字段解释：table->要操作的数据表，不需要加表前缀；
 *              field->要操作的字段；
 *              condition->操作的条件，目前支持字符串，默认变量{$self}为执行行为的用户
 *              rule->对字段进行的具体操作，目前支持四则混合运算，如：1+score*2/2-3
 *              cycle->执行周期，单位（小时），表示$cycle小时内最多执行$max次
 *              max->单个周期内的最大执行次数（$cycle和$max必须同时定义，否则无效）
 * 单个行为后可加 ； 连接其他规则
 * @param string $action 行为id或者name
 * @param int $self 替换规则里的变量为执行用户的id
 * @return boolean|array: false解析出错 ， 成功返回规则数组
 * @author huajie <banhuajie@163.com>
 */
function parse_action($action = null, $self){
    if(empty($action)){
        return false;
    }

    //参数支持id或者name
    if(is_numeric($action)){
        $map = array('id'=>$action);
    }else{
        $map = array('name'=>$action);
    }

    //查询行为信息
    $info = M('Action')->where($map)->find();
    if(!$info || $info['status'] != 1){
        return false;
    }

    //解析规则:table:$table|field:$field|condition:$condition|rule:$rule[|cycle:$cycle|max:$max][;......]
    $rules = $info['rule'];
    $rules = str_replace('{$self}', $self, $rules);
    $rules = explode(';', $rules);
    $return = array();
    foreach ($rules as $key=>&$rule){
        $rule = explode('|', $rule);
        foreach ($rule as $k=>$fields){
            $field = empty($fields) ? array() : explode(':', $fields);
            if(!empty($field)){
                $return[$key][$field[0]] = $field[1];
            }
        }
        //cycle(检查周期)和max(周期内最大执行次数)必须同时存在，否则去掉这两个条件
        if(!array_key_exists('cycle', $return[$key]) || !array_key_exists('max', $return[$key])){
            unset($return[$key]['cycle'],$return[$key]['max']);
        }
    }

    return $return;
}

/**
 * 执行行为
 * @param array $rules 解析后的规则数组
 * @param int $action_id 行为id
 * @param array $user_id 执行的用户id
 * @return boolean false 失败 ， true 成功
 * @author huajie <banhuajie@163.com>
 */
function execute_action($rules = false, $action_id = null, $user_id = null){
    if(!$rules || empty($action_id) || empty($user_id)){
        return false;
    }

    $return = true;
    foreach ($rules as $rule){

        //检查执行周期
        $map = array('action_id'=>$action_id, 'user_id'=>$user_id);
        $map['create_time'] = array('gt', NOW_TIME - intval($rule['cycle']) * 3600);
        $exec_count = M('ActionLog')->where($map)->count();
        if($exec_count > $rule['max']){
            continue;
        }

        //执行数据库操作
        $Model = M(ucfirst($rule['table']));
        $field = $rule['field'];
        $res = $Model->where($rule['condition'])->setField($field, array('exp', $rule['rule']));

        if(!$res){
            $return = false;
        }
    }
    return $return;
}

//基于数组创建目录和文件
function create_dir_or_files($files){
    foreach ($files as $key => $value) {
        if(substr($value, -1) == '/'){
            mkdir($value);
        }else{
            @file_put_contents($value, '');
        }
    }
}

if(!function_exists('array_column')){
    function array_column(array $input, $columnKey, $indexKey = null) {
        $result = array();
        if (null === $indexKey) {
            if (null === $columnKey) {
                $result = array_values($input);
            } else {
                foreach ($input as $row) {
                    $result[] = $row[$columnKey];
                }
            }
        } else {
            if (null === $columnKey) {
                foreach ($input as $row) {
                    $result[$row[$indexKey]] = $row;
                }
            } else {
                foreach ($input as $row) {
                    $result[$row[$indexKey]] = $row[$columnKey];
                }
            }
        }
        return $result;
    }
}

/**
 * 获取表名（不含表前缀）
 * @param string $model_id
 * @return string 表名
 * @author huajie <banhuajie@163.com>
 */
function get_table_name($model_id = null){
    if(empty($model_id)){
        return false;
    }
    $Model = M('Model');
    $name = '';
    $info = $Model->getById($model_id);
    if($info['extend'] != 0){
        $name = $Model->getFieldById($info['extend'], 'name').'_';
    }
    $name .= $info['name'];
    return $name;
}

/**
 * 获取属性信息并缓存
 * @param  integer $id    属性ID
 * @param  string  $field 要获取的字段名
 * @return string         属性信息
 */
function get_model_attribute($model_id, $group = true,$fields=true){
    static $list;

    /* 非法ID */
    if(empty($model_id) || !is_numeric($model_id)){
        return '';
    }

    /* 获取属性 */
    if(!isset($list[$model_id])){
        $map = array('model_id'=>$model_id);
        $extend = M('Model')->getFieldById($model_id,'extend');

        if($extend){
            $map = array('model_id'=> array("in", array($model_id, $extend)));
        }
        $info = M('Attribute')->where($map)->field($fields)->select();
        $list[$model_id] = $info;
    }

    $attr = array();
    if($group){
        foreach ($list[$model_id] as $value) {
            $attr[$value['id']] = $value;
        }
        $sort  = M('Model')->getFieldById($model_id,'field_sort');

        if(empty($sort)){	//未排序
            $group = array(1=>array_merge($attr));
        }else{
            $group = json_decode($sort, true);

            $keys  = array_keys($group);
            foreach ($group as &$value) {
                foreach ($value as $key => $val) {
                    $value[$key] = $attr[$val];
                    unset($attr[$val]);
                }
            }

            if(!empty($attr)){
                $group[$keys[0]] = array_merge($group[$keys[0]], $attr);
            }
        }
        $attr = $group;
    }else{
        foreach ($list[$model_id] as $value) {
            $attr[$value['name']] = $value;
        }
    }
    return $attr;
}

/**
 * 调用系统的API接口方法（静态方法）
 * api('User/getName','id=5'); 调用公共模块的User接口的getName方法
 * api('Admin/User/getName','id=5');  调用Admin模块的User接口
 * @param  string  $name 格式 [模块名]/接口名/方法名
 * @param  array|string  $vars 参数
 */
function api($name,$vars=array()){
    $array     = explode('/',$name);
    $method    = array_pop($array);
    $classname = array_pop($array);
    $module    = $array? array_pop($array) : 'Common';
    $callback  = $module.'\\Api\\'.$classname.'Api::'.$method;
    if(is_string($vars)) {
        parse_str($vars,$vars);
    }
    return call_user_func_array($callback,$vars);
}

/**
 * 根据条件字段获取指定表的数据
 * @param mixed $value 条件，可用常量或者数组
 * @param string $condition 条件字段
 * @param string $field 需要返回的字段，不传则返回整个数据
 * @param string $table 需要查询的表
 * @author huajie <banhuajie@163.com>
 */
function get_table_field($value = null, $condition = 'id', $field = null, $table = null){
    if(empty($value) || empty($table)){
        return false;
    }

    //拼接参数
    $map[$condition] = $value;
    $info = M(ucfirst($table))->where($map);
    if(empty($field)){
        $info = $info->field(true)->find();
    }else{
        $info = $info->getField($field);
    }
    return $info;
}

/**
 * 获取链接信息
 * @param int $link_id
 * @param string $field
 * @return 完整的链接信息或者某一字段
 * @author huajie <banhuajie@163.com>
 */
function get_link($link_id = null, $field = 'url'){
    $link = '';
    if(empty($link_id)){
        return $link;
    }
    $link = M('Url')->getById($link_id);
    if(empty($field)){
        return $link;
    }else{
        return $link[$field];
    }
}

/**
 * 获取文档封面图片
 * @param int $cover_id
 * @param string $field
 * @return 完整的数据  或者  指定的$field字段值
 * @author huajie <banhuajie@163.com>
 */
function get_cover($cover_id, $field = null){
    if(empty($cover_id)){
        return false;
    }
    $picture = M('Picture')->where(array('status'=>1))->getById($cover_id);
    if($field == 'path'){
        if(!empty($picture['url'])){
            $picture['path'] = $picture['url'];
        }else{
            $picture['path'] = __ROOT__.$picture['path'];
        }
    }
    return empty($field) ? $picture : $picture[$field];
}

/**
 * 检查$pos(推荐位的值)是否包含指定推荐位$contain
 * @param number $pos 推荐位的值
 * @param number $contain 指定推荐位
 * @return boolean true 包含 ， false 不包含
 * @author huajie <banhuajie@163.com>
 */
function check_document_position($pos = 0, $contain = 0){
    if(empty($pos) || empty($contain)){
        return false;
    }

    //将两个参数进行按位与运算，不为0则表示$contain属于$pos
    $res = $pos & $contain;
    if($res !== 0){
        return true;
    }else{
        return false;
    }
}

/**
 * 获取数据的所有子孙数据的id值
 * @author 朱亚杰 <xcoolcc@gmail.com>
 */

function get_stemma($pids,Model &$model, $field='id'){
    $collection = array();

    //非空判断
    if(empty($pids)){
        return $collection;
    }

    if( is_array($pids) ){
        $pids = trim(implode(',',$pids),',');
    }
    $result     = $model->field($field)->where(array('pid'=>array('IN',(string)$pids)))->select();
    $child_ids  = array_column ((array)$result,'id');

    while( !empty($child_ids) ){
        $collection = array_merge($collection,$result);
        $result     = $model->field($field)->where( array( 'pid'=>array( 'IN', $child_ids ) ) )->select();
        $child_ids  = array_column((array)$result,'id');
    }
    return $collection;
}

/*************** Doo ********************/
function cutstr_html($string){
    $string = strip_tags($string);
    $string = preg_replace ('/\n/is', '', $string);
    $string = preg_replace ('/ |　/is', '', $string);
    $string = preg_replace ('/&nbsp;/is', '', $string);
    return $string;
}
//随机数
function codestr($length=4,$num=''){
    $str = null;
    $strPol = $num==1 ? '0123456789' : "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
    $max = strlen($strPol)-1;
    for($i=0;$i<$length;$i++){
        $str.=$strPol[rand(0,$max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
    }
    return $str;
}

//实行发送
function sendSMS($mobile,$content,$time='',$mid=''){
    $http = 'http://api.sms.cn/mtutf8/';		//短信接口
    $sms = _setting('sms');
    $uid = $sms['username'];				//用户账号
    $pwd = $sms['password'];							//密码

    $mobileids	 = $mobile . time();	//号码唯一编号
    $data = array
    (
        'uid'=>$uid,					//用户账号
        'pwd'=>md5($pwd.$uid),			//MD5位32密码,密码和用户名拼接字符
        'mobile'=>$mobile,				//号码
        'content'=>$content,			//内容
        'mobileids'=>$mobileids,
        'time'=>$time,					//定时发送
    );
    $res= postSMS($http,$data);			//POST方式提交
    $newRes = explode('&',$res);
    $newRes = explode('=',$newRes[1]);
    return $newRes[1];
}

//短信发送
function postSMS($url,$data=''){
    $post="";
    $row = parse_url($url);
    $host = $row['host'];
    $port = $row['port'] ? $row['port']:80;
    $file = $row['path'];
    while (list($k,$v) = each($data))
    {
        $post .= rawurlencode($k)."=".rawurlencode($v)."&";	//转URL标准码
    }
    $post = substr( $post , 0 , -1 );
    $len = strlen($post);
    $fp = @fsockopen( $host ,$port, $errno, $errstr, 10);
    if (!$fp) {
        return "$errstr ($errno)\n";
    } else {
        $receive = '';
        $out = "POST $file HTTP/1.1\r\n";
        $out .= "Host: $host\r\n";
        $out .= "Content-type: application/x-www-form-urlencoded\r\n";
        $out .= "Connection: Close\r\n";
        $out .= "Content-Length: $len\r\n\r\n";
        $out .= $post;
        fwrite($fp, $out);
        while (!feof($fp)) {
            $receive .= fgets($fp, 128);
        }
        fclose($fp);
        $receive = explode("\r\n\r\n",$receive);
        unset($receive[0]);
        return implode("",$receive);
    }
}
function integralRecord($userid,$data,$adminid=''){
    $obj = M('integral_record');
    $data['num'] = isset($data['num']) ? $data['num'] : 1;
    $data['user_id'] = $userid;
    $data['admin_id'] = $adminid;
    $data['add_time'] = time();
    $data['totalintegral'] = $data['integral']*$data['num'];
    if(M('user')->where(array('id'=>$userid))->setInc('integral',$data['integral'])){
        $obj->create($data);
        return $obj->add();
    }else{
        return false;
    }
}
//只能获取一级菜单
function getLinkMenu($menuid,$field='field',$type='select',$selectid=0,$dispos=0,$limit=0,$condition=array()){
    if(!$menuid) return array();
    $map['menuid'] = array('eq',$menuid);
    $map['status'] = array('eq',1);

    if($dispos==1){
        $map['dispos'] = array('eq',1);
    }
    if(empty($condition)){
        $condition['pid'] = array('eq',0);
    }
    $where = array_merge($map,$condition);
    $obj = M('linkmenu');
    $obj->where($where)->order('ordid desc,id desc');
    if($limit>0){
        $obj->limit($limit);
    }
    $lists =$obj->select();
    $str = '';
    switch($type){
        case 'select':
            $str   = '<select name="'.$field.'" id="'.$field.'">';
            $strs = $menuid !=1 ? '<option value="0">所有</option>' : '';
            $str .=$strs;
            if(!empty($lists)){
                foreach($lists as $v){
                    $s = ($selectid > 0 && $selectid == $v['id']) ? 'selected' : '';
                    $str .= '<option value="'.$v['id'].'" '.$s.'>'.$v['name'].'</option>';
                }
            }
            $str .= '</select>';
            break;
        case 'radio':
            if(!empty($lists)){
                foreach($lists as $v){
                    $s = ($selectid > 0 && $selectid == $v['id']) ? 'checked' : '';
                    $str .= '<input type="radio" name="'.$field.'" id="'.$field.$v['id'].'" value="'.$v['id'].'" '.$s.' /><label for="'.$field.$v['id'].'">'.$v['name'].'</label>';
                }
            }
            break;
        case 'checkbox':
            if(!empty($lists)){
                foreach($lists as $v){
                    $s = (is_array($selectid) && !empty($selectid)) ? (in_array($v['id'],$selectid) ?  'checked' : '') : '';
                    $str .= '<input type="checkbox" name="'.$field.'[]" id="'.$field.$v['id'].'" value="'.$v['id'].'" '.$s.' /><label for="'.$field.$v['id'].'">'.$v['name'].'</label>';
                }
            }
            break;
        case 'array':
            $str = $lists;
            break;
        defalut:
            $str   = '<select name="'.$field.'" id="'.$field.'"><option value="0">所有</option>';
            if(!empty($lists)){
                foreach($lists as $v){
                    $s = ($selectid > 0 && $selectid == $v['id']) ? 'selected' : '';
                    $str .= '<option value="'.$v['id'].'" '.$s.'>'.$v['name'].'</option>';
                }
            }
            $str .= '</select>';
            break;
    }

    return $str;
}

function getLinkMenuNameById($id,$return='str',$str=','){
    if($id){
        if(is_numeric($id)){
            $info = M('linkmenu')->where(array('id'=>$id))->field('id,name')->find();
            return $info['name'];
        }else{
            $ids = str_replace('|',',',trim($id,'|'));
            $where['id'] = array('in',$ids);
            $list = M('linkmenu')->where($where)->field('name')->select();
            $name = array();
            foreach($list as $v){
                $name[] = $v['name'];
            }
            if($return=='str'){
                return implode($str,$name);
            }else{
                return $name;
            }
        }

    }else{
        return '';
    }

}
function getHouseName($id=0,$all=false,$field='*',$model='house'){
    if($id){
        $info = M($model)->where(array('id'=>$id))->field($field)->find();
        return $all ? $info : $info['title'];
    }else{
        return '';
    }

}
function Z($str,$id,$name,$menuid=0){
    $str = str_replace('@id@',$id,$str);
    $str = str_replace('@menuid@',$menuid,$str);
    $str = str_replace('@name@',$name,$str);

    return $str;
}

/**
 * 前台地址
 * @param $url
 * @param string $arr
 * @return string
 */
function HU($url,$arr=''){
    $str = '';
    if($arr){
        foreach($arr as $k=>$v){
            $str .= '&'.$k.'='.$v;
        }
    }
    $url = explode('/',$url);
    return d_name('hw')."/index.php?m=Home&c={$url[0]}&a={$url[1]}{$str}";
}

/*******
 * 会员后台URL
 */
function MU($url,$arr=''){
    $str = '';
    if($arr){
        foreach($arr as $k=>$v){
            $str .= '&'.$k.'='.$v;
        }
    }
    $url = explode('/',$url);
    return  d_name('hw')."/user.php?m=Member&c={$url[0]}&a={$url[1]}{$str}";
}

function _md5($val){
    return md5(md5(md5(substr(md5($val),5))));
}



/**
 * @param $user_id
 * @param $data
 * @param int $type (1=积分记录，2为余额变动记录);
 * @param string $adminid
 * @return bool|mixed
 *
 */
function Record($user_id,$data,$type=1){
    $obj = D('UserRecord');
    $data['user_id'] = $user_id;
    $data['option_time'] = time();
    $data['option_date'] = date("Y-m-d");
    $data['type'] = $type;
    if($type==2){
        $field =  'blance';
        $data['money'] = $data['num'];
    }else{
        $field = 'point';
        $data['point'] = $data['num'];
    }
    if(D('UserAccount')->where(array('user_id'=>$user_id))->setInc($field,$data['num'])){
        unset($data['num']);
        $obj->create($data);
        return $obj->add();
    }else{
        return false;
    }
}

/**
 * 获取分类
 */
function getRentalCate($pid=0){
    $cate = M('RentalCate')->where(array('status'=>1,'pid'=>$pid))->order('ordid desc')->select();
    return $cate;
}

function getUrl($action,$key,$url,$val=''){
    $url_model = C('URL_MODEL');
    $url[$key] = $val;
    if($val==''){
        unset($url[$key]);
    }
    if($_GET['id']){    //按小区ID获取
        $url['id'] = intval($_GET['id']);
    }
    if($url_model== 2){
        $urlArr = array();
        $urlArr['house']['index'] = array('alias','price','tags','roomType','houseType','houseStatus','houseStatus','renovationType','floor','sort','group','metro','key');
        $urlArr['used']['index'] = array('alias','totalPrice','area','orientations','mating','renovationType','usedType','room','hall','kitchen','toilet','balcony','other','sort','metro','key');
        $urlArr['rental']['index'] = array('alias','price','area','orientations','rentalMode','houseType','mating','renovationType','room','hall','kitchen','toilet','balcony','payType','other','sort','metro','key');
        $urlArr['estate']['index'] = array('alias','houseType','years','sort','metro','key');
        $urlArr['estate']['used'] = array('totalPrice','area','orientations','mating','renovationType','room','hall','kitchen','toilet','balcony','other','sort');
        $urlArr['estate']['rental'] = array('price','area','orientations','rentalMode','mating','renovationType','room','hall','kitchen','toilet','balcony','payType','other','sort');
        $c = strtolower(CONTROLLER_NAME);
        $a = strtolower(ACTION_NAME);
        foreach($urlArr[$c][$a] as $v){
            if($v=='alias'){
                $url[$v] = $url[$v] ? $url[$v] : 'all';
            }else{
                $url[$v] = $url[$v] ? $url[$v] : 0;
            }
        }
    }
    return U($action,$url);
}


/**
 * 获取扩展表数据并遍历到对应的id上
 * @param $menu_id
 */
function getLinkMenuFor($menu_id='',$field=''){
    $where = array('status'=>1);
    if(is_array($menu_id)){
        $where['menuid'] = array('in',implode(',',$menu_id));
    }else if(is_numeric($menu_id)){
        $where['menuid'] = array('eq',$menu_id);
    }
    $list = M('linkmenu')->where($where)->order('ordid desc')->select();
    if(count($list)){
        $arr = array();
        foreach($list as $v){
            $arr[$v['menuid']][$v['id']] = $v['name'];
            if($field){
                $arr[$v['menuid']][$v['id']] = $v;
            }
        }
    }
    return $arr ? $arr : false;
}

//按id或取会员信息
function getUserInfo($user_id,$key='username'){
    $fex = C('DB_PREFIX');
    $userInfo = M('user as u')
         ->join('left join '.$fex.'user_info as ui on u.id = ui.user_id')
         ->where(array('u.id'=>$user_id))
         ->field('u.*,ui.head_ico,ui.housing,ui.level,ui.true_name,ui.qq,ui.hot_line,ui.address,ui.company_name')
         ->find();
    if($key){
        return $userInfo[$key];
    }else{
        return $userInfo;
    }
}

//判断是否登陆并获取会员做这处
function getUser(){
    $user_id = cookie('fangcms_uid');
    $user = M('user')->where(array('id'=>$user_id))->find();
    $keys = md5($user['password'].$user['id']);
    if($keys!=cookie('fangcms_keys')){
        return false;
    }
    $map['user_id'] = $user['id'];
    $user['userInfo'] = D("UserInfo")->where($map)->find();
    $user['account']  = D("UserAccount")->where($map)->field('blance,point,freeze')->find();
    $user['companyWeb'] = M('CompanyWeb')->where($map)->find();
    $user['userCate'] = M('userCate')->where(array('id'=>$user['cate_id']))->find();
    return $user;
}

function getLoginUser(){
    $user_id = $_SESSION['userInfo']['id'];
    $user = M('user')->where(array('id'=>$user_id))->find();
    return $user;
}

//获取类型
function getTypeName($key=''){
    $arr = array(
        'esf'=>'二手房',
        'rental'=>'出租房',
    );
    if($key){
        return $arr[$key];
    }
    return $arr;
}

//获取户型
function getHouseType($house_id,$key=0){
    $houseType = M('house_type')->where(array('status'=>1,'house_id'=>$house_id))->order('room asc')->select();
    if($houseType){
        $list = $val= array();
        $count = 0;
        foreach($houseType as $v){
            $list[$v['room']] += 1;
            $house_type[$v['room']][] = $v;
            $count +=1;
        }
    }
    if($key){
        return array('list'=>$list,'house_type'=>$house_type,'count'=>$count);
    }else{
        return $list;
    }
}

//获取对应的楼盘类型
function getHouseTypeStr($typeIds,$typeArr){
    $ids = explode('|',trim($typeIds,'|'));
    $str = array();
    foreach($ids as $v){
       $str[] = $typeArr[$v];
    }
    $html = implode(',',$str);
    return $html;
}

//短信模版
function smsTpl($key='pass_tpl',$data = array()){
    $sms = _setting('sms',1);
    if($sms[$key]){
        $str = $sms[$key];
        if(strpos($str,'sitename')){
            $str = str_replace("sitename",$data['sitename'],$str);
        }
        if(strpos($str,'phone')){
            $str = str_replace("phone",$data['phone'],$str);
        }
        if(strpos($str,'code')){
            $str = str_replace("code",$data['code'],$str);
        }
        if(strpos($str,'username')){
            $str = str_replace("username",$data['username'],$str);
        }
        return $str;
    }
}

/**
 * 获取分页显示
 * @param $where
 * @param int $pageSize
 */
function getPageShow($model,$where,$pageSize=10){
    $m = M($model);
    $count = $m->where($where)->count();
    $pager = new \Org\Util\Page($count, $pageSize);
    $list = $m->where($where)->order('id desc')->limit($pager->firstRow.','.$pager->listRows)->select();
    $page = $pager->show();
    return array('page'=>$page,'list'=>$list,'count'=>$count);
}

//把分类对应到ID上
function cateFor($cate='',$model=''){
    if($model){
        $cate = M($model)->where(array('status'=>1))->field('id,name')->select();
    }
    $arr = array();
    foreach($cate as $v){
        $arr[$v['id']] = $v['name'];
    }
    return $arr;
}

//解决状态
function solveStatus($key=''){
    $arr = array(
        1=>'待解决',
        2=>'已解决',
    );
    return $key ? $arr[$key] : $arr;
}

//获取单条广告
function getOneAd($id,$w='auto',$h='auto'){
    $ad = M('ad')->where(array('id'=>$id))->find();
    if($w or $h){
        if($ad['url']){
            $ad = "<a target='_blank' href='".$ad['url']."'><img alt=".$ad['desc']." width=".$w." height=".$h." src=".$ad['img']."></a>";
        }else{
            $ad = "<img width=".$w." height=".$h." src=".$ad['img'].">";
        }
    }
    return $ad;
}

//获取房型参数
function getHouseSet($house){
    $arr['address'] = explode('|',$house['address']);
    $arr['tel'] = explode('|',$house['tel']);
    if(!$arr['tel'][0]){
        $contact = _setting('contact');
        $arr['tel'] = explode('|',$contact['universal_phone']);
    }

    $arr['tags'] = explode('|',trim($house['tags'],'|'));
    $arr['house_type']= M('house_type')->where(array('status'=>1,'is_rec'=>1,'house_id'=>$house['id']))->field('id,name,area,room')->order('ordid desc')->limit(3)->select();
    $arr['pic_count'] = M('house_picture')->where(array('house_id'=>$house['id'],'status'=>1))->count();
    $arr['news'] = M('article')->where(array('house_id'=>$house['id'],'status'=>1))->order('id desc')->find();
    $arr['ask_count'] = M('ask')->where(array('house_id'=>$house['id'],'status'=>1))->count();
    return $arr;
}

//数字转中文
function numTurnCn($key=''){
    $arr = array(
        1=>'一',
        2=>'二',
        3=>'三',
        4=>'四',
        5=>'五',
        6=>'六',
        7=>'七',
        8=>'八',
        9=>'九'
    );

    return $key ? $arr[$key] : $arr;
}

//获取回答内空
function getAnswerOne($answer_id,$key='info'){
    $info = M('answer')->where(array('answer_id'=>$answer_id))->find();
    if($key){
        return $info[$key];
    }else{
        return $info;
    }
}

//获取小区
function getEstate($id,$key=''){
    $info = M('estate')->where(array('id'=>$id))->find();
    return $key ? $info[$key] : $info;
}

//获取文件列表
function getArticleList($cate_id=0,$limit=10,$field='id,title'){
    $where = array('status'=>1,'add_time'=>array('lt',time()));
    if(is_numeric($cate_id)){
        $cate = new \Org\Yike\Category();
        $ac = M('article_cate')->where(array('status'=>1))->select();
        $cate_ids = $cate->getChiIds($ac,$cate_id,1);
        array_push($cate_ids,$cate_id);
    }
    $where['cate_id'] = array('in',$cate_ids ? $cate_ids : $cate_id);

    $list = M('article')->where($where)->limit($limit)->order('id desc')->field($field)->select();
    return $list;
}

//获取回答列表
function getAnswerList($limit=4){
    $fex = C('DB_PREFIX');
    $answerObj = M("answer as a");
    $list = $answerObj->join('left join '.$fex.'ask as ask on a.ask_id = ask.id')
        ->field('a.id,a.info,ask.id as ask_id,ask.title')
        ->where('a.status = 1')
        ->order('a.id desc')
        ->limit($limit)
        ->select();
    return $list;
}

//订单类型
function order_type($model,$key=''){
    $arr = array();
    $arr['house'] = array(
        1=>'免费电话',
        2=>'报名看房',
        3=>'降价通知',
        4=>'团购报名',
    );
    $arr['used'] = array(
        1=>'免费电话',
        2=>'预约看房'
    );
    $arr['rental'] = array(
        1=>'免费电话',
        2=>'预约看房'
    );
    return $key ? $arr[$model][$key] : $arr[$model];
}

function getStatus($model='article',$key=''){
    $arr = array();
    $arr['article'] = array(
        1=>'已发布',
        2=>'被退回',
        3=>'有效',
        4=>'已删除',
        5=>'存档'
    );
    $arr['ask'] = array(
        1=>'已发布',
        2=>'被退回',
        3=>'待审核',
        4=>'已删除',
        5=>'存档'
    );
    $arr['rental'] = array(
        1=>'已发布',
        2=>'被退回',
        3=>'待审核',
        4=>'已删除',
        5=>'存档'
    );
    $arr['used'] = array(
        0=>'待审核',
        1=>'已发布',
        2=>'被退回',
        3=>'有效',
        4=>'已删除',
        5=>'存档'
    );
    $arr['deal'] = array(
        0=>'禁用',
        1=>'未审核',
        2=>'财务已审核',
        3=>'跟单已审核',
    );
    $arr['user'] = array(
        0=>'待审核',
        1=>'已审核',
        2=>'财务已审核',
        3=>'跟单已审核',
    );
    return $key ? $arr[$model][$key] : $arr[$model];
}

function getUserInfoConf($model='',$key=''){
    $arr = array();
    $arr['id_type'] = array(
        1=>'身份证',
        2=>'工作证',
        3=>'军官证',
        4=>'学生证',
        5=>'护照'
    );
    $arr['edu'] = array(
        1=>'初中',
        2=>'高中',
        3=>'中专',
        4=>'大专',
        5=>'本科',
        6=>'硕士',
        7=>'博士',
        8=>'其他'
    );
    $arr['job'] = array(
        1=>'政府机关/干部',
        2=>'计算机',
        3=>'网络',
        4=>'商业/贸易',
        5=>'银行/金融/证劵/保险',
        6=>'税务',
        7=>'旅游/饭店',
        8=>'房地产',
        10=>'法律/司法',
        11=>'文化/教育',
        12=>'媒介/广告',
        13=>'农/渔/林/畜牧业',
        14=>'矿业/制造业',
        15=>'学生',
        16=>'自由业',
        17=>'其它'
    );

    if($model){
        return $key ? $arr[$model][$key] : $arr[$model];
    }else{
        return $arr;
    }
}

function getGroup($id,$key=''){
    $info = M('group')->where(array('id'=>$id))->find();
    return  $key ? $info[$key] : $info;
}

//URL显示
function urlShow($key='ask',$id){
    $hw = d_name('hw');
    $arr = array(
       'ask'=>array(
           '0'=>$hw."/index.php?m=Home&c=Ask&a=detail&id=".$id,
           '1'=>$hw."/index.php/Ask/detail/id/{$id}.html",
           '2'=>$hw."/wenda/{$id}.html",
           '3'=>$hw."/index.php?s=/Ask/detail/id/{$id}.html"
       ),
        'news'=>array(
            '0'=>$hw."/index.php?m=Home&c=News&a=detail&id=".$id,
            '1'=>$hw."/index.php/News/detail/id/{$id}.html",
            '2'=>$hw."/News-detail-id-{$id}.html",
            '3'=>$hw."/index.php?s=/News/detail/id/{$id}.html",
            '5'=>$hw."/zixun/{$id}.html",
        ),
        'rental'=>array(
            '0'=>$hw."/index.php?m=Home&c=Rental&a=detail&id=".$id,
            '1'=>$hw."/index.php/Rental/detail/id/{$id}.html",
            '2'=>$hw."/chuzu/{$id}.html",
            '3'=>$hw."/index.php?s=/Rental/detail/id/{$id}.html"
        ),
        'used'=>array(
            '0'=>$hw."/index.php?m=Home&c=Used&a=detail&id=".$id,
            '1'=>$hw."/index.php/Used/detail/id/{$id}.html",
            '2'=>$hw."/esf/{$id}.html",
            '3'=>$hw."/index.php?s=/Used/detail/id/{$id}.html"
        ),
        'house'=>array(
            '0'=>$hw."/index.php?m=Home&c=House&a=detail&id=".$id,
            '1'=>$hw."/index.php/House/detail/id/{$id}.html",
            '2'=>$hw."/luopan/{$id}.html",
            '3'=>$hw."/index.php?s=/House/detail/id/{$id}.html"
        ),
        'store'=>array(
            '0'=>$hw."/index.php?m=Home&c=Store&a=index&uid=".$id,
            '1'=>$hw."/index.php/Store/index/uid/{$id}.html",
            '2'=>$hw."/dianpu/{$id}.html",
            '3'=>$hw."/index.php?s=/Store/index/uid/{$id}.html"
        )
    );
    $file = APP_PATH.'/Home/Conf/config.php';
    $conf = require $file;
    return $arr[$key][$conf['URL_MODEL']];
}

/**
 * 获取分类的Ids
 * @param $id
 * @param $model
 */
function getCateIds($id,$model='area_cate'){
    $cate_list = M($model)->where(array('status'=>1))->select();
    $cate = new \Org\Yike\Category();
    $ids = $cate::getChiIds($cate_list,$id,1);
    array_push($ids,$id);
    return $ids;
}

function getUserCount($user_id,$model='used'){
    $count = M($model)->where(array('user_id'=>$user_id,'status'=>1))->count();
    return $count ? $count : 0;
}

//按用户ID获取房源信息
function getAgencyUserInfo($user_id){
    $data = array();
    $data['used'] = M('used')->where(array('status'=>1,'user_id'=>$user_id))->order('id desc')->limit(3)->select();
    $data['rental'] = M('rental')->where(array('status'=>1,'user_id'=>$user_id))->order('id desc')->limit(3)->select();
    return $data;
}
//生成二维码
/*
 * 第一个参数$text，就是上面代码里的URL网址参数，
　*　第二个参数$outfile默认为否，不生成文件，只将二维码图片返回，否则需要给出存放生成二维码图片的路径
　*　第三个参数$level默认为L，这个参数可传递的值分别是L(QR_ECLEVEL_L，7%)，M(QR_ECLEVEL_M，15%)，
  *  Q(QR_ECLEVEL_Q，25%)，H(QR_ECLEVEL_H，30%)。这个参数控制二维码容错率，不同的参数表示二维码可被覆盖的区域百分比。
　*　利用二维维码的容错率，我们可以将头像放置在生成的二维码图片任何区域。
　*　第四个参数$size，控制生成图片的大小，默认为4
　* 第五个参数$margin，控制生成二维码的空白区域大小
　*　第六个参数$saveandprint，保存二维码图片并显示出来，$outfile必须传递图片路径。
 * */
function createQR ($text, $fileName, $size=4, $level='L', $margin=2, $saveandprint=false){
    vendor('phpqrcode.phpqrcode');
    $baseFilePath = 'Uploads/qrcode/';
    $object = new \QRcode();
    $filePath = $baseFilePath.$fileName;
    $object->png($text, $filePath, $level, $size, $margin, $saveandprint);
    return '/'.$filePath;
}